package com.xhwl.logistics.open;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.iotdata.mettler.WeighDTO;
import com.xhwl.common.dto.cent.iotdata.vehicleschedule.VehicleScheduleRequestsDTO;
import com.xhwl.common.dto.cent.iotdata.vehicleschedule.VehicleScheduleResponseDTO;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.device.DeviceProduct;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.pojo.cent.sdata.OrganizationType;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.dto.http.DaHuaResponseDTO;
import com.xhwl.logistics.dto.push.CarInDaHuaIccDTO;
import com.xhwl.logistics.entity.*;
import com.xhwl.logistics.service.business.VehicleAlarmBusinessService;
import com.xhwl.logistics.service.business.VehicleCommonBusinessService;
import com.xhwl.logistics.service.cent.*;
import com.xhwl.logistics.service.impl.*;
import com.xhwl.logistics.util.AESUtil;
import com.xhwl.logistics.util.AboutDateUtil;
import com.xhwl.logistics.util.ServletUtils;
import com.xhwl.logistics.util.UploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
//@RestController
public class DaHuaIccPushController {


    @Autowired
    private IDeviceService iDeviceService;

    @Autowired
    private QueryDeviceService queryDeviceService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private VehicleCarServiceImpl vehicleCarService;

    @Autowired
    private VehiclePassageServiceImpl vehiclePassageService;

    @Autowired
    private VehicleAccessRecordServiceImpl vehicleAccessRecordService;

    @Autowired
    private VehicleAlarmBusinessService vehicleAlarmBusinessService;

    @Autowired
    private VehicleCommonBusinessService vehicleCommonBusinessService;

    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private IOrganizationTypeService organizationTypeService;

    @Autowired
    private IIotDataService iotDataService;

    @Autowired
    private VehicleAreaServiceImpl vehicleAreaService;

    @Autowired
    @Qualifier("posterInfoThread") //批量导入线程
    private ThreadPoolExecutor executor;

    /**
     * 大华推送所用常量
     */
    private static final Integer normal_access = 1;
    private static final Integer car_in = 0;
    private static final Integer car_out = 1;
    private static final String resCodeErr = "9030";
    private static final String res_code_true = "000000";
    private static final String noCarNum = "N000001";
    private static final String device_type = "GATE";
    private static final String event_type_in = "IN";
    private static final String event_type_out = "OUT";
    private static final String vehicle_schedule_true = "Y";
    private static final String is_open = "1";
    private static final String is_not_open = "2";
    private static final String daHuaEva = "/evo-apigw";
    private static final String amountActual = "0";
    private static final String hongMenCarInRecord = "HM_ENTER_COMMAND";
    private static final String hongMenCarOutRecord = "HM_CAR_EXIT";
    private static final String hongMenSuccessCode = "0";
    private static final String hongMenRecordNull = "null";


    //出行记录中第三方车场id为空字符串，用于避免有些功能因为null而导致失败
    private static final String parkId = "";

    /**
     * 通过项目id查询出行记录
     */
    private Wrapper<VehicleAccessRecord> conditionForVehicleAccessRecord(Integer projectId){
        return new LambdaQueryWrapper<VehicleAccessRecord>().eq(
                VehicleAccessRecord::getProjectId, projectId
        );
    }

    private Wrapper<VehicleCar> conditionForCar(String plateNumber, Integer projectId){
        LambdaQueryWrapper<VehicleCar> vehicleCarLambdaQueryWrapper = new LambdaQueryWrapper<>();
        return vehicleCarLambdaQueryWrapper.eq(VehicleCar::getPlateNumber,plateNumber)
                .eq(VehicleCar::getProjectId,projectId)
                .orderByDesc(VehicleCar::getCreatedAt);
    }

    private Wrapper<VehiclePassage> conditionPassage(String thirdPassageId, Integer projectId){
        LambdaQueryWrapper<VehiclePassage> vehiclePassageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        return vehiclePassageLambdaQueryWrapper.eq(VehiclePassage::getProjectId,projectId)
                .eq(VehiclePassage::getThirdPassageId,thirdPassageId);
    }

    private Wrapper<VehiclePassage> conditionPassageByName(String passageName, Integer projectId){
        LambdaQueryWrapper<VehiclePassage> vehiclePassageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        return vehiclePassageLambdaQueryWrapper.eq(VehiclePassage::getProjectId, projectId)
                .eq(VehiclePassage::getPassageName, passageName);
    }

    private Wrapper<VehicleAccessRecord> conditionVehicleAccessRecord(String recordId, Integer projectId){
        LambdaQueryWrapper<VehicleAccessRecord> vehicleAccessRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        return vehicleAccessRecordLambdaQueryWrapper.eq(StringUtils.isNotEmpty(recordId), VehicleAccessRecord::getRecordId, recordId)
                .eq(VehicleAccessRecord::getProjectId, projectId)
                .eq(VehicleAccessRecord::getStatus, car_in);
    }

    private Wrapper<VehicleAccessRecord> condititonForCatRecord(String plateNumber, Integer projectId, String entryTime){
        LambdaQueryWrapper<VehicleAccessRecord> vehicleAccessRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        return vehicleAccessRecordLambdaQueryWrapper.eq(VehicleAccessRecord::getPlateNumber, plateNumber)
                .eq(VehicleAccessRecord::getProjectId, projectId)
                .eq(VehicleAccessRecord::getStatus, car_in)
                .eq(StringUtils.isNotEmpty(entryTime), VehicleAccessRecord::getEnterTime, AboutDateUtil.stringToDateDaHuaICC(entryTime))
                .orderByDesc(VehicleAccessRecord::getUpdatedAt);
    }

    /**
     * 获取大华ICC的项目id
     */
    private VehicleIntegratedConfigBO getDaHuaICCProjectId(){
        List<DeviceProduct> deviceProductList = iDeviceService.list();
        //将ICC智能物联管理平台演示的productId与对应的实现类进行绑定
        DeviceProduct deviceProduct = deviceProductList.stream().filter(s -> {
            if (s.getName().contains("大华ICC平台")) {
                return true;
            } else {
                return false;
            }
        }).findAny().orElse(null);
        if(deviceProduct!=null){
            //获取所有车场系统对应的集成配置
            List<VehicleIntegratedConfigBO> vehicleIntegratedConfigBOList = queryDeviceService.queryIntegratedConfigs();
            VehicleIntegratedConfigBO vehicleIntegratedConfigBO = vehicleIntegratedConfigBOList.stream().filter(s -> {
                if(s.getVehicleSystemInfoBO().getProductId()!=null){
                    if (StringUtils.equals(s.getVehicleSystemInfoBO().getProductId().toString(), deviceProduct.getId().toString())) {
                        return true;
                    }else{
                        return false;
                    }
                }
                else {
                    return false;
                }
            }).findAny().orElse(null);
            if(vehicleIntegratedConfigBO!=null){
                return vehicleIntegratedConfigBO;
            }else{
                log.info("未给大华ICC配置集成配置！");
                return null;
            }
        }else{
            log.info("未匹配到“ICC智慧物联%”的产品！");
            return null;
        }
    }

    /**
     * 大华ICC出行记录的卡类型转换为中台卡类型
     */
    private Integer convertDaHuaCarRecordType(Integer cardType){
        switch (cardType){
            case 0:
                return 1;
            case 1:
                return 3;
            case 2:
                return 0;
            case 3:
                return 99;
            default:
                return null;
        }
    }

    /**
     * 大华ICC进出类型转换为中台进出类型
     */
    private Integer convertDaHuaInOutType(Integer carInOutType){
        switch (carInOutType){
            case 1:
                return 0;
            case 2:
                return 1;
            default:
                return null;
        }
    }

    /**
     * 大华ICC进出方式转换为车行中台进出方式
     */
    private Integer convertDaHuaInType(Integer actType){
        switch (actType){
            case 0:
            case 1:
            case 2:
                return 1;
            case 3:
                return 2;
            default:
                return 99;
        }
    }

    /**
     * 大华ICC的车牌颜色转换为中交兴路要求的车牌颜色
     */
    private String convertDaHuaCarNumColor(String carNumColor){
        switch (carNumColor){
            case "0":
                return "BLUE";
            case "1":
                return "YELLOW";
            default:
                return null;
        }
    }

    /**
     * 将红门的车牌类型转换为中台的车牌类型
     */
    private Integer convertHongMenCardType(String cardType){
        switch (cardType){
            case "固定车":
                return 1;
            default:
                return 0;
        }
    }

    /**
     * 大华预进场的开闸和不开闸返回值
     */
    private Map<String, Object> returnDaHuaICCPreIn(Boolean openWay){
        Map<String, Object> respData = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        respData.put("resCode", res_code_true);
        if(openWay){
            params.put("isOpen", is_open);
        }else{
            params.put("isOpen", "3");
        }
        respData.put("data", params);
        return respData;
    }

    /**
     * 大华预出场的开闸和不开闸的返回值
     */
    private Map<String, Object> returnDaHuaICCPreOut(Boolean openWay){
        Map<String, Object> respData = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        respData.put("resCode", res_code_true);
        if(openWay){
            params.put("amountActual", amountActual);
            params.put("amountReceivable", amountActual);
            params.put("isOpen", is_open);
        }else{
            params.put("amountActual", amountActual);
            params.put("amountReceivable", amountActual);
            params.put("isOpen", "3");
            params.put("isPayByLineAmount", "2");
        }
        respData.put("data", params);
        return respData;
    }

    /**
     * 蒙牛红门推送进记录和出记录的功能，定制化需求
     */
    @PostMapping("/hong-men-mn/car-in-out")
    public void carInOutHongMen(HttpServletRequest request, HttpServletResponse response){
        //获取请求中的车辆进出记录的json信息
        String carInOutStr = this.onGettingBody(request);
        //由于红门推送的图片信息为一串图片流，比较多，故暂不建议打开红门出行记录的日志
//        log.info("红门推送的出入记录为：{}", carInOutStr);
        JSONObject carInOutObj = JSONObject.parseObject(carInOutStr);
        log.info("红门推送出入记录，车牌号为：{}", JSONObject.parseObject(carInOutObj.getString("content")).getString("car_plate_no"));
        Map<String, Object> respData = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        respData.put("command", carInOutObj.getString("command"));
        respData.put("parking_id", carInOutObj.getString("parking_id"));
        respData.put("message_id", carInOutObj.getString("message_id"));
        VehicleIntegratedConfigBO vehicleIntegratedConfigBO = this.getDaHuaICCProjectId();
        Project project = vehicleCommonBusinessService.getProjectById(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());

        //表示为进场记录
        if(StringUtils.equals(hongMenCarInRecord, carInOutObj.getString("command"))){
            JSONObject carInObj = JSONObject.parseObject(carInOutObj.getString("content"));
            VehicleAccessRecord vehicleAccessRecord = new VehicleAccessRecord();
            vehicleAccessRecord.setProjectId(project.getId());
            vehicleAccessRecord.setProjectCode(project.getCode());
            vehicleAccessRecord.setProjectName(project.getName());
            vehicleAccessRecord.setPlateNumber(carInObj.getString("car_plate_no"));
            List<VehicleCar> vehicleCarList = vehicleCarService.list(conditionForCar(carInObj.getString("car_plate_no"), project.getId()));
            if(!vehicleCarList.isEmpty()){
                vehicleAccessRecord.setOwnerName(vehicleCarList.get(0).getOwnerName());
                vehicleAccessRecord.setOwnerPhone(vehicleCarList.get(0).getOwnerPhone());
                vehicleAccessRecord.setCardType(vehicleCarList.get(0).getCardType());
            }
            else {
                vehicleAccessRecord.setCardType(this.convertHongMenCardType(carInObj.getString("passport_type_name")));
            }
            String imgUrl = "";
            //图片上传到minio中
            try{
                UploadUtils uploadUtils = new UploadUtils();
                imgUrl = uploadUtils.uploadImgBase64(carInObj.getString("car_picture"));
            }catch (Exception e){
                log.error("红门图片下载失败！");
            }
            vehicleAccessRecord.setEnterPictureUrl(imgUrl);
            vehicleAccessRecord.setEnterTime(AboutDateUtil.stringToDate(carInObj.getString("enter_time")));
            vehicleAccessRecord.setEnterType(normal_access);
            List<VehiclePassage> vehiclePassageList = vehiclePassageService.list(conditionPassageByName(carInObj.getString("channel_name"), project.getId()));
            if(!vehiclePassageList.isEmpty()){
                vehicleAccessRecord.setEnterPassageId(vehiclePassageList.get(0).getId());
                vehicleAccessRecord.setEnterPassageName(vehiclePassageList.get(0).getPassageName());
            }
            vehicleAccessRecord.setRecordId(carInObj.getString("record_no"));
            vehicleAccessRecord.setStatus(car_in);
            vehicleAccessRecord.setParkId(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemark());
            vehicleAccessRecordService.save(vehicleAccessRecord);
        }
        //表示为出场记录
        else if(StringUtils.equals(hongMenCarOutRecord, carInOutObj.getString("command"))){
            JSONObject carOutObj = JSONObject.parseObject(carInOutObj.getString("content"));
            //查询出该出场记录对应的进场记录
            List<VehicleAccessRecord> vehicleAccessRecordList
                    = vehicleAccessRecordService.list(conditionVehicleAccessRecord(carOutObj.getString("enter_record_no"), project.getId()));
            if(!vehicleAccessRecordList.isEmpty() && StringUtils.isNotEmpty(carOutObj.getString("enter_record_no"))
             && StringUtils.equals(hongMenRecordNull, carOutObj.getString("enter_record_no"))){
                VehicleAccessRecord vehicleAccessRecord = vehicleAccessRecordList.get(0);
                String imgUrl = "";
                //图片上传到minio中
                try{
                    UploadUtils uploadUtils = new UploadUtils();
                    imgUrl = uploadUtils.uploadImgBase64(carOutObj.getString("car_picture"));
                }catch (Exception e){
                    log.error("红门图片下载失败！");
                }
                vehicleAccessRecord.setExitPictureUrl(imgUrl);
                vehicleAccessRecord.setExitType(normal_access);
                vehicleAccessRecord.setExitTime(AboutDateUtil.stringToDate(carOutObj.getString("exit_time")));
                List<VehiclePassage> vehiclePassageList = vehiclePassageService.list(conditionPassageByName(carOutObj.getString("channel_name"), project.getId()));
                if(!vehiclePassageList.isEmpty()){
                    vehicleAccessRecord.setExistPassageId(vehiclePassageList.get(0).getId());
                    vehicleAccessRecord.setExitPassageName(vehiclePassageList.get(0).getPassageName());
                }
                vehicleAccessRecord.setStatus(car_out);
                vehicleAccessRecordService.updateById(vehicleAccessRecord);
            }else{
                VehicleAccessRecord vehicleAccessRecordAdd = new VehicleAccessRecord();
                vehicleAccessRecordAdd.setProjectId(project.getId());
                vehicleAccessRecordAdd.setProjectCode(project.getCode());
                vehicleAccessRecordAdd.setProjectName(project.getName());
                vehicleAccessRecordAdd.setPlateNumber(carOutObj.getString("car_plate_no"));
                List<VehicleCar> vehicleCarList = vehicleCarService.list(conditionForCar(carOutObj.getString("car_plate_no"), project.getId()));
                if(!vehicleCarList.isEmpty()){
                    vehicleAccessRecordAdd.setOwnerName(vehicleCarList.get(0).getOwnerName());
                    vehicleAccessRecordAdd.setOwnerPhone(vehicleCarList.get(0).getOwnerPhone());
                    vehicleAccessRecordAdd.setCardType(vehicleCarList.get(0).getCardType());
                }
                else {
                    vehicleAccessRecordAdd.setCardType(this.convertHongMenCardType(carOutObj.getString("passport_type_name")));
                }
                String imgUrl = "";
                //图片上传到minio中
                try{
                    UploadUtils uploadUtils = new UploadUtils();
                    imgUrl = uploadUtils.uploadImgBase64(carOutObj.getString("car_picture"));
                }catch (Exception e){
                    log.error("红门图片下载失败！");
                }
                vehicleAccessRecordAdd.setExitPictureUrl(imgUrl);
                vehicleAccessRecordAdd.setExitTime(AboutDateUtil.stringToDate(carOutObj.getString("exit_time")));
                vehicleAccessRecordAdd.setExitType(normal_access);
                List<VehiclePassage> vehiclePassageList = vehiclePassageService.list(conditionPassageByName(carOutObj.getString("channel_name"), project.getId()));
                if(!vehiclePassageList.isEmpty()){
                    vehicleAccessRecordAdd.setExistPassageId(vehiclePassageList.get(0).getId());
                    vehicleAccessRecordAdd.setExitPassageName(vehiclePassageList.get(0).getPassageName());
                }
                vehicleAccessRecordAdd.setRecordId(carOutObj.getString("enter_record_no"));
                vehicleAccessRecordAdd.setStatus(car_out);
                vehicleAccessRecordAdd.setParkId(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemark());
                vehicleAccessRecordService.save(vehicleAccessRecordAdd);
            }
        }
        else{
            log.info("该推送记录既不是进记录也不是出记录");
        }
        respData.put("timestamp", String.valueOf(System.currentTimeMillis()));
        params.put("result_code", hongMenSuccessCode);
        params.put("message", "success");
        respData.put("content", params);
        ServletUtils.RespToWrite(response, respData);
    }

    /**
     * 大华预出场纪录推送，当前这个接口只满足蒙牛项目
     */
    @PostMapping("/da-hua-icc-mn/pre-car-out")
    public void preCarOut(HttpServletRequest request, HttpServletResponse response)throws Exception{
        //获取请求中的字符串，并将其解密成相应的JSONObject对象
        String preCarOutEncrypt = this.onGettingBody(request);
        String preCarOutString = AESUtil.daHuaICCDecrypt(preCarOutEncrypt, request);
        log.info("大华ICC预出场推送：da-hua-icc push data for pre car out, data is {}", preCarOutString);
        JSONObject preCarOutObject = JSONObject.parseObject(preCarOutString);

        if(preCarOutObject != null && preCarOutObject.getString("actType") != null){
            //获取大华ICC集成配置
            VehicleIntegratedConfigBO vehicleIntegratedConfigBO = getDaHuaICCProjectId();
            if(vehicleIntegratedConfigBO == null){
                log.info("未找到大华ICC的集成配置！");
                ServletUtils.RespToWrite(response, this.returnDaHuaICCPreOut(false));
                return;
            }
            //判断是否通知车辆调度
            VehiclePassage vehiclePassage = vehiclePassageService.getOne(conditionPassage(preCarOutObject.getString("sluiceDevChnId"),
                    vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId()));
            if(vehiclePassage == null){
                log.info(preCarOutObject.getString("carNum") + "该道闸通道信息未同步到平台中，清先同步");
                ServletUtils.RespToWrite(response, this.returnDaHuaICCPreOut(false));
                return;
            }
            VehicleArea vehicleArea = vehicleAreaService.getById(vehiclePassage.getAreaId());
            if(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemarkUnion().equals(vehicleArea.getRemark())){
                log.info(preCarOutObject.getString("carNum") + "将驶出货车区的闸机，现在开始请求车辆调度");
            }else if (vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemark().equals(vehicleArea.getRemark())){
                log.info(preCarOutObject.getString("carNum") + "将驶出办公区的闸机，不对其做出处理");
                ServletUtils.RespToWrite(response, this.returnDaHuaICCPreOut(false));
                return;
            }else{
                log.info(preCarOutObject.getString("carNum") + "将驶出未知区的闸机，不对其做出处理");
                ServletUtils.RespToWrite(response, this.returnDaHuaICCPreOut(false));
                return;
            }

            //通过通道中的备注字段查询相应的设备信息
            DevicePageQuery deviceQuery = new DevicePageQuery();
            deviceQuery.setProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
            deviceQuery.setThirdDeviceId(vehiclePassage.getRemark());
            List<DeviceDTO> deviceDTOS = iDeviceService.listDevice(null, deviceQuery);
            if(!deviceDTOS.isEmpty()){
                //组装车辆调度类，请求车辆是否允许进入
                DeviceDTO deviceDTO = deviceDTOS.get(0);
                VehicleScheduleRequestsDTO vehicleScheduleRequestsDTO = this.deviceInfoToPosition(deviceDTO);
                if(vehicleScheduleRequestsDTO == null){
                    ServletUtils.RespToWrite(response, this.returnDaHuaICCPreOut(false));
                    return;
                }
                vehicleScheduleRequestsDTO.setProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
                vehicleScheduleRequestsDTO.setDeviceType(device_type);
                vehicleScheduleRequestsDTO.setDeviceName(deviceDTO.getName());
                vehicleScheduleRequestsDTO.setSerialNumber(deviceDTO.getThirdDeviceId());
                vehicleScheduleRequestsDTO.setTruckNo(preCarOutObject.getString("carNum"));
                if(preCarOutObject.getString("carNumcolor") != null){
                    String carNumcolor = convertDaHuaCarNumColor(preCarOutObject.getString("carNumcolor"));
                    if(carNumcolor != null){
                        vehicleScheduleRequestsDTO.setPlateColor(carNumcolor);
                    }
                }
                vehicleScheduleRequestsDTO.setEventType(event_type_out);
                log.info("车辆预出场请求车辆调度的报文参数为：{}", JSONObject.toJSONString(vehicleScheduleRequestsDTO));
                ResultJson<VehicleScheduleResponseDTO> resultJson = iotDataService.onCheckingTruckEnter(vehicleScheduleRequestsDTO);
                log.info("请求车辆调度的结果为：{}", JSONObject.toJSONString(resultJson));
                if(resultJson == null || !resultJson.getState()){
                    log.info("车辆调度接口返回样子的不是常态");
                    ServletUtils.RespToWrite(response, this.returnDaHuaICCPreOut(false));
                    return;
                }else{
                    if(vehicle_schedule_true.equals(resultJson.getResult().getIsAllowEntry())){
                        log.info(preCarOutObject.getString("carNum") + "允许出去");
                        ServletUtils.RespToWrite(response, this.returnDaHuaICCPreOut(true));
                        return;
                    }
                    else{
                        log.info(preCarOutObject.getString("carNum") + "不允许出去");
                        ServletUtils.RespToWrite(response, this.returnDaHuaICCPreOut(false));
                        return;
                    }
                }
            }
        }

        log.info("该次请求可能不是大华ICC请求的");
        ServletUtils.RespToWrite(response, this.returnDaHuaICCPreOut(false));
    }

    /**
     * 大华预进场记录推送，当前这个接口只满足蒙牛项目
     */
    @PostMapping("/da-hua-icc-mn/pre-car-in")
    public void preCarIn(HttpServletRequest request, HttpServletResponse response)throws Exception{
        //获取请求中的字符串，并将其解密成相应的JSONObject对象
        String preCarInEncrypt = this.onGettingBody(request);
        String preCarInString = AESUtil.daHuaICCDecrypt(preCarInEncrypt, request);
        log.info("大华ICC预进场推送: da-hua-icc push data for pre car in, data is {}", preCarInString);
        JSONObject preCarInObject = JSONObject.parseObject(preCarInString);

        if(preCarInObject != null && preCarInObject.getString("bizSn") != null){
            //通过大华ICC获取集成配置
            VehicleIntegratedConfigBO vehicleIntegratedConfigBO = getDaHuaICCProjectId();
            if(vehicleIntegratedConfigBO == null){
                log.info("未找到大华ICC的集成配置！");
                ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(false));
                return;
            }
            //判断是否通知车辆调度
            VehiclePassage vehiclePassage = vehiclePassageService.getOne(conditionPassage(preCarInObject.getString("sluiceDevChnId"),
                    vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId()));
            if(vehiclePassage == null){
                log.info(preCarInObject.getString("carNum") + "该道闸通道信息未同步到平台中，清先同步");
                ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(false));
                return;
            }
            VehicleArea vehicleArea = vehicleAreaService.getById(vehiclePassage.getAreaId());
            if(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemarkUnion().equals(vehicleArea.getRemark())){
                log.info(preCarInObject.getString("carNum") + "将驶入货车区的闸机，现在开始请求车辆调度");
            }else if (vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemark().equals(vehicleArea.getRemark())){
                log.info(preCarInObject.getString("carNum") + "将驶入办公区的闸机，不对其做出处理");
                ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(false));
                return;
            }else{
                log.info(preCarInObject.getString("carNum") + "将驶入未知区的闸机，不对其做出处理");
                ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(false));
                return;
            }

            //通过通道中的备注字段查询相应的设备信息
            DevicePageQuery deviceQuery = new DevicePageQuery();
            deviceQuery.setProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
            deviceQuery.setThirdDeviceId(vehiclePassage.getRemark());
            List<DeviceDTO> deviceDTOS = iDeviceService.listDevice(null, deviceQuery);
            if(!deviceDTOS.isEmpty()){
                //组装车辆调度类，请求车辆是否允许进入
                DeviceDTO deviceDTO = deviceDTOS.get(0);
                VehicleScheduleRequestsDTO vehicleScheduleRequestsDTO = this.deviceInfoToPosition(deviceDTO);
                if(vehicleScheduleRequestsDTO == null){
                    ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(false));
                    return;
                }
                vehicleScheduleRequestsDTO.setProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
                vehicleScheduleRequestsDTO.setDeviceType(device_type);
                vehicleScheduleRequestsDTO.setDeviceName(deviceDTO.getName());
                vehicleScheduleRequestsDTO.setSerialNumber(deviceDTO.getThirdDeviceId());
                vehicleScheduleRequestsDTO.setTruckNo(preCarInObject.getString("carNum"));
                if(preCarInObject.getString("carNumcolor") != null){
                    String carNumcolor = convertDaHuaCarNumColor(preCarInObject.getString("carNumcolor"));
                    if(carNumcolor != null){
                        vehicleScheduleRequestsDTO.setPlateColor(carNumcolor);
                    }
                }
                vehicleScheduleRequestsDTO.setEventType(event_type_in);
                log.info("车辆预进场请求车辆调度的报文参数为：{}", JSONObject.toJSONString(vehicleScheduleRequestsDTO));
                ResultJson<VehicleScheduleResponseDTO> resultJson = iotDataService.onCheckingTruckEnter(vehicleScheduleRequestsDTO);
                log.info("请求车辆调度的结果为：{}", JSONObject.toJSONString(resultJson));
                if(resultJson == null || !resultJson.getState()){
                    log.info("车辆调度接口返回样子的不是常态");
                    ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(false));
                    return;
                }else{
                    if(vehicle_schedule_true.equals(resultJson.getResult().getIsAllowEntry())){
                        if(resultJson.getResult().getWeightType() != null && StringUtils.isNotEmpty(resultJson.getResult().getWeightType())){
                            //1、判断地磅上是否存在车辆，由于摄像头这边还没开发完成，所以默认是没车的
                            //2、告知地磅称重类型、并开始称重，延迟30秒开始称重
                            executor.execute(()->{
                                try {
                                    log.info("接收到称重参数，将于30秒后开始称重");
                                    Thread.sleep(30000);
                                    log.info("开始称重");
                                    WeighDTO weighDTO = this.vehicleScheduleToWeighDTO(resultJson.getResult(), vehicleIntegratedConfigBO, preCarInObject);
                                    ResultJson weigh = iotDataService.weigh(weighDTO);
                                    log.info("调用开始称重的返回结果为：{}",JSONObject.toJSONString(weigh));
                                } catch (InterruptedException e) {
                                    log.error("该线程被阻塞了");
                                    throw new BusinessException("线程阻塞");
                                }
                            });
//                            WeighDTO weighDTO = this.vehicleScheduleToWeighDTO(resultJson.getResult(), vehicleIntegratedConfigBO, preCarInObject);
//                            ResultJson weigh = iotDataService.weigh(weighDTO);
                            log.info(preCarInObject.getString("carNum") + "允许进入");
                            ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(true));
                            return;
                        }
                        log.info(preCarInObject.getString("carNum") + "允许进入");
                        ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(true));
                        return;
                    }
                    else{
                        log.info(preCarInObject.getString("carNum") + "不允许进入");
                        ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(false));
                        return;
                    }
                }
            }
        }

        log.info("该次请求可能不是大华ICC请求的");
        ServletUtils.RespToWrite(response, this.returnDaHuaICCPreIn(false));
    }

    /**
     * 大华进记录推送
     */
    @PostMapping("/da-hua-icc/car-in")
    public DaHuaResponseDTO carIn(HttpServletRequest request)throws Exception {
        String carInEncrypt = onGettingBody(request);
        //解密
        String carInString = AESUtil.daHuaICCDecrypt(carInEncrypt, request);
        log.info("大华ICC进场推送: da-hua-icc push data for car in, data is {}", carInString);
        CarInDaHuaIccDTO carInDaHuaIccDTO = JSONObject.parseObject(carInString, CarInDaHuaIccDTO.class);
        return this.carInMethod(carInDaHuaIccDTO);
    }

    /**
     * 大华出记录推送
     */
    @PostMapping("/da-hua-icc/car-out")
    public DaHuaResponseDTO carOut(HttpServletRequest request) throws Exception {
        String carOutEncrypt = onGettingBody(request);
        //解密
        String carOutStr = AESUtil.daHuaICCDecrypt(carOutEncrypt, request);
        log.info("大华ICC出场推送: da-hua-icc push data for car out, data is {}", carOutStr);
        CarInDaHuaIccDTO carOutDaHuaIccDTO = JSONObject.parseObject(carOutStr, CarInDaHuaIccDTO.class);
        return this.carOutMethod(carOutDaHuaIccDTO);
    }

    /**
     * 蒙牛大华ICC进记录推送（定制）
     */
    @PostMapping("/da-hua-icc-mn/car-in")
    public DaHuaResponseDTO carInMn(HttpServletRequest request)throws Exception {
        String carInEncrypt = onGettingBody(request);
        String carInString = AESUtil.daHuaICCDecrypt(carInEncrypt, request);
        //解密
        log.info("大华ICC进场推送: da-hua-icc push data for car in, data is {}", carInString);
        CarInDaHuaIccDTO carInDaHuaIccDTO = JSONObject.parseObject(carInString, CarInDaHuaIccDTO.class);
        executor.execute(()->syncCarInEvent(carInDaHuaIccDTO));
        return this.carInMethod(carInDaHuaIccDTO);
    }

    /**
     * 蒙牛大华ICC出记录推送（定制）
     */
    @PostMapping("/da-hua-icc-mn/car-out")
    public DaHuaResponseDTO carOutMn(HttpServletRequest request)throws Exception{
        String carOutEncrypt = onGettingBody(request);
        //解密
        String carOutStr = AESUtil.daHuaICCDecrypt(carOutEncrypt, request);
        log.info("大华ICC出场推送: da-hua-icc push data for car out, data is {}", carOutStr);
        CarInDaHuaIccDTO carOutDaHuaIccDTO = JSONObject.parseObject(carOutStr, CarInDaHuaIccDTO.class);
        executor.execute(()->syncCarOutEvent(carOutDaHuaIccDTO));
        return this.carOutMethod(carOutDaHuaIccDTO);
    }

    /**
     * 大华ICC的进记录推送
     */
    private DaHuaResponseDTO carInMethod(CarInDaHuaIccDTO carInDaHuaIccDTO){
        if(carInDaHuaIccDTO != null){
            if(carInDaHuaIccDTO.getBizSn() != null){
                VehicleIntegratedConfigBO vehicleIntegratedConfigBO = getDaHuaICCProjectId();
                if(vehicleIntegratedConfigBO==null){
                    throw new BusinessException("未配置大华ICC的集成配置！");
                }
                Project project = vehicleCommonBusinessService.getProjectById(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
                if(project != null){
                    VehicleAccessRecord vehicleAccessRecord = new VehicleAccessRecord();
                    vehicleAccessRecord.setProjectId(project.getId());
                    vehicleAccessRecord.setProjectCode(project.getCode());
                    vehicleAccessRecord.setProjectName(project.getName());
                    vehicleAccessRecord.setPlateNumber(carInDaHuaIccDTO.getCarNum());
                    List<VehicleCar> vehicleCarList = vehicleCarService.list(conditionForCar(carInDaHuaIccDTO.getCarNum(), project.getId()));
                    if(!vehicleCarList.isEmpty()){
                        vehicleAccessRecord.setOwnerName(vehicleCarList.get(0).getOwnerName());
                        vehicleAccessRecord.setOwnerPhone(vehicleCarList.get(0).getOwnerPhone());
                        vehicleAccessRecord.setCardType(vehicleCarList.get(0).getCardType());
                    }
                    else{
                        vehicleAccessRecord.setCardType(convertDaHuaCarRecordType(Integer.parseInt(carInDaHuaIccDTO.getActType())));
                    }
                    //图片组装
                    String imgUrlHttp = this.assemVehicleImg(carInDaHuaIccDTO.getCarImgUrl(), vehicleIntegratedConfigBO);
                    String imgUrl = "";
                    //图片上传到minio中
                    try{
                        imgUrl = UploadUtils.uploadImg(imgUrlHttp);
                    }catch (Exception e){
                        log.error("大华ICC图片下载失败！");
                    }
                    vehicleAccessRecord.setEnterPictureUrl(imgUrl);
                    vehicleAccessRecord.setEnterTime(AboutDateUtil.stringToDateDaHuaICC(carInDaHuaIccDTO.getArriveTime()));
                    vehicleAccessRecord.setEnterType(normal_access);
                    VehiclePassage vehiclePassage = vehiclePassageService.getOne(conditionPassage(carInDaHuaIccDTO.getSluiceDevChnId(), project.getId()));
                    if(vehiclePassage!=null){
                        vehicleAccessRecord.setEnterPassageName(vehiclePassage.getPassageName());
                        vehicleAccessRecord.setEnterPassageId(vehiclePassage.getId());
                    }
                    vehicleAccessRecord.setRecordId(carInDaHuaIccDTO.getBizSn());
                    vehicleAccessRecord.setStatus(car_in);
                    vehicleAccessRecord.setParkId(carInDaHuaIccDTO.getParkingLot());
                    vehicleAccessRecordService.save(vehicleAccessRecord);
                }
            }
        }else{
            DaHuaResponseDTO daHuaResponseDTO = new DaHuaResponseDTO();
            daHuaResponseDTO.setResCode(resCodeErr);
            return daHuaResponseDTO;
        }
        return new DaHuaResponseDTO();
    }

    /**
     * 大华ICC的出记录推送
     */
    private DaHuaResponseDTO carOutMethod(CarInDaHuaIccDTO carOutDaHuaIccDTO){
        if(carOutDaHuaIccDTO != null){
            if(carOutDaHuaIccDTO.getBizSn() != null){
                VehicleIntegratedConfigBO vehicleIntegratedConfigBO = getDaHuaICCProjectId();
                if(vehicleIntegratedConfigBO == null){
                    throw new BusinessException("未配置大华ICC的集成配置！");
                }
                Project project = vehicleCommonBusinessService.getProjectById(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
                if(project != null){
                    List<VehicleAccessRecord> vehicleAccessRecordList = vehicleAccessRecordService.list(condititonForCatRecord(
                            carOutDaHuaIccDTO.getCarNum(), project.getId(), carOutDaHuaIccDTO.getArriveTime()));
                    //根据车牌号和进入时间查询出最新的进记录时，更新出行记录
                    if (!vehicleAccessRecordList.isEmpty()){
                        VehicleAccessRecord vehicleAccessRecord = vehicleAccessRecordList.get(0);
                        //图片组装
                        String imgUrlHttp = this.assemVehicleImg(carOutDaHuaIccDTO.getCarImgUrl(), vehicleIntegratedConfigBO);
                        String imgUrl = "";
                        //图片上传到minio中
                        try{
                            imgUrl = UploadUtils.uploadImg(imgUrlHttp);
                        }catch (Exception e){
                            log.error("大华ICC图片下载失败！");
                        }
                        vehicleAccessRecord.setExitPictureUrl(imgUrl);
                        vehicleAccessRecord.setExitTime(AboutDateUtil.stringToDateDaHuaICC(carOutDaHuaIccDTO.getLeaveTime()));
                        vehicleAccessRecord.setExitType(normal_access);
                        VehiclePassage vehiclePassage = vehiclePassageService.getOne(conditionPassage(carOutDaHuaIccDTO.getSluiceDevChnId(), project.getId()));
                        if(vehiclePassage!=null){
                            vehicleAccessRecord.setExitPassageName(vehiclePassage.getPassageName());
                            vehicleAccessRecord.setExistPassageId(vehiclePassage.getId());
                        }
                        vehicleAccessRecord.setStatus(car_out);
                        vehicleAccessRecordService.updateById(vehicleAccessRecord);
                    }
                    //若未查询出进记录，新增出行记录
                    else {
                        VehicleAccessRecord vehicleAccessRecordAdd = new VehicleAccessRecord();
                        vehicleAccessRecordAdd.setProjectId(project.getId());
                        vehicleAccessRecordAdd.setProjectCode(project.getCode());
                        vehicleAccessRecordAdd.setProjectName(project.getName());
                        vehicleAccessRecordAdd.setPlateNumber(carOutDaHuaIccDTO.getCarNum());
                        List<VehicleCar> vehicleCarList = vehicleCarService.list(conditionForCar(carOutDaHuaIccDTO.getCarNum(), project.getId()));
                        if(!vehicleCarList.isEmpty()){
                            vehicleAccessRecordAdd.setOwnerName(vehicleCarList.get(0).getOwnerName());
                            vehicleAccessRecordAdd.setOwnerPhone(vehicleCarList.get(0).getOwnerPhone());
                            vehicleAccessRecordAdd.setCardType(vehicleCarList.get(0).getCardType());
                        }
                        else{
                            vehicleAccessRecordAdd.setCardType(convertDaHuaCarRecordType(Integer.parseInt(carOutDaHuaIccDTO.getActType())));
                        }
                        //图片组装
                        String imgUrlHttp = this.assemVehicleImg(carOutDaHuaIccDTO.getCarImgUrl(), vehicleIntegratedConfigBO);
                        String imgUrl = "";
                        //图片上传到minio中
                        try{
                            imgUrl = UploadUtils.uploadImg(imgUrlHttp);
                        }catch (Exception e){
                            log.error("大华ICC图片下载失败！");
                        }
                        vehicleAccessRecordAdd.setExitPictureUrl(imgUrl);
                        vehicleAccessRecordAdd.setExitTime(AboutDateUtil.stringToDateDaHuaICC(carOutDaHuaIccDTO.getArriveTime()));
                        vehicleAccessRecordAdd.setExitType(normal_access);
                        VehiclePassage vehiclePassage = vehiclePassageService.getOne(conditionPassage(carOutDaHuaIccDTO.getSluiceDevChnId(), project.getId()));
                        if(vehiclePassage!=null){
                            vehicleAccessRecordAdd.setExitPassageName(vehiclePassage.getPassageName());
                            vehicleAccessRecordAdd.setExistPassageId(vehiclePassage.getId());
                        }
                        vehicleAccessRecordAdd.setRecordId(carOutDaHuaIccDTO.getBizSn());
                        vehicleAccessRecordAdd.setStatus(car_out);
                        vehicleAccessRecordAdd.setParkId(carOutDaHuaIccDTO.getParkingLot());
                        vehicleAccessRecordService.save(vehicleAccessRecordAdd);
                    }
                }
            }
        }else{
            DaHuaResponseDTO daHuaResponseDTO = new DaHuaResponseDTO();
            daHuaResponseDTO.setResCode(resCodeErr);
            return daHuaResponseDTO;
        }
        return new DaHuaResponseDTO();
    }

    /**
     * 车辆进道闸通知车辆调度
     */
    private void syncCarInEvent(CarInDaHuaIccDTO carInDaHuaIccDTO){
        if(carInDaHuaIccDTO.getBizSn() != null){
            VehicleIntegratedConfigBO vehicleIntegratedConfigBO = getDaHuaICCProjectId();
            if(vehicleIntegratedConfigBO == null){
                log.info("未配置大华ICC的集成配置");
                return;
            }
            //判断是否通知车辆调度
            VehiclePassage vehiclePassage = vehiclePassageService.getOne(conditionPassage(carInDaHuaIccDTO.getSluiceDevChnId(),
                    vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId()));
            if(vehiclePassage == null){
                log.info(carInDaHuaIccDTO.getCarNum() + "该道闸通道信息未同步到平台中，清先同步");
                return;
            }
            VehicleArea vehicleArea = vehicleAreaService.getById(vehiclePassage.getAreaId());
            if(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemarkUnion().equals(vehicleArea.getRemark())){
                log.info(carInDaHuaIccDTO.getCarNum() + "已经驶入货车区的闸机，现在开始请求车辆调度");
            }else if (vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemark().equals(vehicleArea.getRemark())){
                log.info(carInDaHuaIccDTO.getCarNum() + "已经驶入办公区的闸机，不对其做出处理");
                return;
            }else{
                log.info(carInDaHuaIccDTO.getCarNum() + "已经驶入未知区的闸机，不对其做出处理");
                return;
            }
            //通过通道中的备注字段查询相应的设备信息
            DevicePageQuery deviceQuery = new DevicePageQuery();
            deviceQuery.setProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
            deviceQuery.setThirdDeviceId(vehiclePassage.getRemark());
            List<DeviceDTO> deviceDTOS = iDeviceService.listDevice(null, deviceQuery);
            if(!deviceDTOS.isEmpty()){
                DeviceDTO deviceDTO = deviceDTOS.get(0);
                VehicleScheduleRequestsDTO vehicleScheduleRequestsDTO = this.deviceInfoToPosition(deviceDTO);
                if(vehicleScheduleRequestsDTO == null){
                    return;
                }
                vehicleScheduleRequestsDTO.setProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
                vehicleScheduleRequestsDTO.setDeviceType(device_type);
                vehicleScheduleRequestsDTO.setDeviceName(deviceDTO.getName());
                vehicleScheduleRequestsDTO.setSerialNumber(deviceDTO.getThirdDeviceId());
                vehicleScheduleRequestsDTO.setTruckNo(carInDaHuaIccDTO.getCarNum());
                vehicleScheduleRequestsDTO.setEventType(event_type_in);
                log.info("车辆进场请求车辆调度的报文参数为：{}", JSONObject.toJSONString(vehicleScheduleRequestsDTO));
                ResultJson<VehicleScheduleResponseDTO> resultJson = iotDataService.onSyncingTruckEvents(vehicleScheduleRequestsDTO);
                log.info("请求车辆调度的结果为：{}", JSONObject.toJSONString(resultJson));
            }else{
                log.info("通过{}未找到关联设备", vehiclePassage.getPassageName());
            }
        }else{
            log.info("此次进场记录可能不是大华ICC推送的");
        }
    }

    /**
     * 车辆出道闸通知车辆调度
     */
    private void syncCarOutEvent(CarInDaHuaIccDTO carOutDaHuaIccDTO){
        if(carOutDaHuaIccDTO.getBizSn() != null){
            VehicleIntegratedConfigBO vehicleIntegratedConfigBO = getDaHuaICCProjectId();
            if(vehicleIntegratedConfigBO == null){
                log.info("未配置大华ICC的集成配置");
                return;
            }
            //判断是否通知车辆调度
            VehiclePassage vehiclePassage = vehiclePassageService.getOne(conditionPassage(carOutDaHuaIccDTO.getSluiceDevChnId(),
                    vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId()));
            if(vehiclePassage == null){
                log.info(carOutDaHuaIccDTO.getCarNum() + "该道闸通道信息未同步到平台中，清先同步");
                return;
            }
            VehicleArea vehicleArea = vehicleAreaService.getById(vehiclePassage.getAreaId());
            if(vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemarkUnion().equals(vehicleArea.getRemark())){
                log.info(carOutDaHuaIccDTO.getCarNum() + "已经驶出货车区的闸机，现在开始请求车辆调度");
            }else if (vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getRemark().equals(vehicleArea.getRemark())){
                log.info(carOutDaHuaIccDTO.getCarNum() + "已经驶出办公区的闸机，不对其做出处理");
                return;
            }else{
                log.info(carOutDaHuaIccDTO.getCarNum() + "已经驶出未知区的闸机，不对其做出处理");
                return;
            }
            //通过通道中的备注字段查询相应的设备信息
            DevicePageQuery deviceQuery = new DevicePageQuery();
            deviceQuery.setProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
            deviceQuery.setThirdDeviceId(vehiclePassage.getRemark());
            List<DeviceDTO> deviceDTOS = iDeviceService.listDevice(null, deviceQuery);
            if(!deviceDTOS.isEmpty()){
                DeviceDTO deviceDTO = deviceDTOS.get(0);
                VehicleScheduleRequestsDTO vehicleScheduleRequestsDTO = this.deviceInfoToPosition(deviceDTO);
                if(vehicleScheduleRequestsDTO == null){
                    return;
                }
                vehicleScheduleRequestsDTO.setProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
                vehicleScheduleRequestsDTO.setDeviceType(device_type);
                vehicleScheduleRequestsDTO.setDeviceName(deviceDTO.getName());
                vehicleScheduleRequestsDTO.setSerialNumber(deviceDTO.getThirdDeviceId());
                vehicleScheduleRequestsDTO.setTruckNo(carOutDaHuaIccDTO.getCarNum());
                vehicleScheduleRequestsDTO.setEventType(event_type_out);
                log.info("车辆出场请求车辆调度的报文参数为：{}", JSONObject.toJSONString(vehicleScheduleRequestsDTO));
                ResultJson<VehicleScheduleResponseDTO> resultJson = iotDataService.onSyncingTruckEvents(vehicleScheduleRequestsDTO);
                log.info("请求车辆调度的结果为：{}", JSONObject.toJSONString(resultJson));
            }else{
                log.info("通过{}未找到关联设备", vehiclePassage.getPassageName());
            }
        }else{
            log.info("此次出场记录可能不是大华ICC推送的");
        }
    }

    private String onGettingBody(HttpServletRequest request) {
        try {
            BufferedReader reader = request.getReader();
            char[] buf = new char[512];
            int len = 0;
            StringBuffer contentBuffer = new StringBuffer();
            while ((len = reader.read(buf)) != -1) {
                contentBuffer.append(buf, 0, len);
            }
            return contentBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 组装车场图片的地址
     */
    private String assemVehicleImg(String daHuaImg, VehicleIntegratedConfigBO vehicleIntegratedConfigBO){
        URL daHuaUrl = null;
        try {
            daHuaUrl = new URL(daHuaImg);
        } catch (MalformedURLException e) {
            log.info("大华ICC推送的图片地址不是http地址");
            return vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost() + daHuaEva + daHuaImg;
        }
        log.info("大华ICC推送的图片地址是http地址");
        return vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost() + daHuaEva + daHuaUrl.getPath()+ "?" + daHuaUrl.getQuery();
    }

    /**
     * 根据设备信息，获取设备的点位信息
     */
    private VehicleScheduleRequestsDTO deviceInfoToPosition(DeviceDTO deviceDTO){
        VehicleScheduleRequestsDTO vehicleScheduleRequestsDTO = new VehicleScheduleRequestsDTO();
        Organization organization = organizationService.getById(deviceDTO.getOrganizationId());
        //由于space类型的组织的编码不是存储在组织表中，而是存储在space表中
        if(!StringUtils.isEmpty(organization.getCode())){
            vehicleScheduleRequestsDTO.setPositionId(organization.getCode());
        }else{
            ResultJson spaceResult = organizationService.detail(null, organization.getId());
            log.info("组织表里面没有code信息，请求space结果为：{}，", JSONObject.toJSONString(spaceResult));
            if (spaceResult == null || !spaceResult.getState()){
                log.info("获取space信息失败");
                return null;
            }
            JSONObject spaceObject = JSONObject.parseObject(
                    JSONObject.parseObject(JSONObject.toJSONString(spaceResult.getResult())).getString("data"));
            if(StringUtils.isEmpty(spaceObject.getString("code"))){
                log.info("space中没有code信息");
                return null;
            }
            vehicleScheduleRequestsDTO.setPositionId(spaceObject.getString("code"));
        }
        vehicleScheduleRequestsDTO.setPositionName(organization.getName());
//        organizationService.list(null);
        List<OrganizationType> organizationTypeList = organizationTypeService.list(null);
        organizationTypeList.stream().filter(organizationType1 -> organizationType1.getId().equals(organization.getType()))
                .findAny().ifPresent(organizationType -> vehicleScheduleRequestsDTO.setPositionType(organizationType.getCode()));

        return vehicleScheduleRequestsDTO;
    }

    /**
     * 组装称重的请求参数
     */
    private WeighDTO vehicleScheduleToWeighDTO(VehicleScheduleResponseDTO vehicleScheduleResponseDTO
            , VehicleIntegratedConfigBO vehicleIntegratedConfigBO, JSONObject preCarInObject){
        WeighDTO weighDTO = new WeighDTO();
        weighDTO.setProjectId(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
        weighDTO.setPlateNumber(preCarInObject.getString("carNum"));
        weighDTO.setTransportOrderCode(vehicleScheduleResponseDTO.getTransportOrderCode());
        weighDTO.setPo(vehicleScheduleResponseDTO.getPoId());
        weighDTO.setCommandId(vehicleScheduleResponseDTO.getCommandId());
        weighDTO.setWeightType(vehicleScheduleResponseDTO.getWeightType());
        return weighDTO;
    }
}
